<?php
namespace Wap\Controller;
use Think\Controller;
class IndexController extends Controller{
	protected $allowFromWeb = true;//是否允许非微信浏览器访问
	protected $strict_mode = true;//是否获取访问者openid
	protected $allow_anonymous = true;//是否允许匿名访问
	protected $token;
	protected $wechat_id;

	protected $indexPagePath = 'Index/exchange';//默认入口页面

	public function _initialize(){
		$agent = $_SERVER['HTTP_USER_AGENT'];
		if(!$this->allowFromWeb && strpos($agent,"MicroMessenger")===FALSE) {
			exit('请使用微信浏览器访问！');
		}
        //从url中获取到token
        //$this->token = 'anuxzf1435128586';
		//$this->token = 'heru';
		$getToken = I('get.token','','trim');
		if(!$getToken){
			$this->token = session('token');
		}else{
			$this->token = $getToken;
		}
		session('token',$this->token);
		$this->wxConfig = $this->getWxConfig();
		if($this->wxConfig == null ){// || !$this->token
			exit('非法访问, not found wxConfig!');
		}
		if(ACTION_NAME =='oauth2callback') return;
		if(!is_valid_openid($this->wechat_id) && strpos($agent,"MicroMessenger")){//$this->strict_mode){//strpos($agent,"MicroMessenger")){
			if(is_valid_openid(session('wechat_id-'.$this->token))){
				$this->wechat_id = session('wechat_id-'.$this->token);
			}
			else{
				$this->getOpenid();
			}
		}
		else{
			session('wechat_id-'.$this->token,$this->wechat_id);
		}
		// for test
        //$this->wechat_id = 'ojNXcwJhKx5_wZWaTfGacOX7IZ0Q';


        $this->assign('token',$this->token);
        $this->assign('wechat_id',$this->wechat_id);
        $this->assign('wxset',$this->wxConfig);
		define('RES','/Public/'.MODULE_NAME);
		define('STATICS','/Public/Common');

		if($this->wechat_id){
		    $this->userinfo = M('juejin_users')->where(['open_id'=>$this->wechat_id])->find();
			$this->wechatinfo = M('wechat_user')->where(['open_id'=>$this->wechat_id])->find();
			$this->sharecount = M('juejin_users')->where(['shareid'=>$this->userinfo['id']])->count();
			$this->assign('wechatinfo',$this->wechatinfo);
			$this->assign('userinfo',$this->userinfo);
			$this->assign('sharecount',$this->sharecount);
		}
	    
		//parent::_initialize();
	}
	
	public function index(){
		$this->exchange();
	}
	public function addressform(){
	    $this->display();
	}

	public function exchange(){
		$prizeinfo = M('juejin_prize')->where('status=1 AND count-odd>0')->find();
		$this->assign('prizeinfo',$prizeinfo);
		$this->assign('page','exchange');
	    $this->display($this->indexPagePath);
	}

	public function integral(){
		$loginfo = M('juejin_integral_log')->where(['userid'=>$this->userinfo['id']])->order('createtime desc')->limit(30)->select();
		$this->assign('loginfo',$loginfo);
		$this->assign('page','integral');
	    $this->display();
	}
	public function rank(){
		$sql =  "SELECT *,`sp_wechat_user`.`headimgurl` as headimg_url,`sp_juejin_users`.`id` as `userid` FROM `sp_juejin_users` LEFT JOIN `sp_wechat_user` ON `sp_juejin_users`.`open_id` = `sp_wechat_user`.`open_id` WHERE `sp_wechat_user`.`token`='$this->token' ORDER BY `sp_juejin_users`.`integral` DESC,`sp_juejin_users`.`id` DESC LIMIT 0,110";
		$rank = M()->query($sql);
		$myrank = 0;//count($rank);
		foreach ($rank as $item) {
			$myrank++;
			if($item['userid']==$this->userinfo['id']){
				break;	
			}
		}
		if($myrank>100){
			$myrank = '100+';
		}
		$this->assign('rank',$rank);
		$this->assign('myrank',$myrank);
		$this->assign('page','rank');

	    $this->display();
	}
	public function getCommonInfo(){

	}
	/*生成合图*/
	public function invitecode(){

	}


	public function getOpenid(){
		//认证后的服务号才能使用该接口
		if(isset($_GET['_from'])) session('ORIGIN_URL',$_GET['_from']);
		else session('ORIGIN_URL',urlencode(__SELF__));
		if($this->wxConfig['wxtype']=='服务号'&&$this->wxConfig['is_certified']==1){
			$util = new \Spark\Wechat\WechatUtil($this->wxConfig['appid'], $this->wxConfig['appsecret']);
			//$util->getOAuth2Code(C('wap_domain').'/Wap/Wap/oauth2callback.html?token='.$this->token);
			$util->getOAuth2Code(C('wap_domain').'/Wap/Index/oauth2callback.html?token='.$this->token,'snsapi_userinfo','userinfo');//2016-1-23
		}
		else if(!$this->allow_anonymous){
			exit('<h2>无法获取您的身份信息！</h2>');
		}
	}
	protected function getWxConfig(){
		if(S('WXCONFIG')==false){
			$config = M('wxuser','sp_')->where(['token'=>$this->token])->find();
			S('WXCONFIG',$config);
			return $config;
		}
		else return S('WXCONFIG');
	}
	public function oauth2callback(){
		if(isset($_GET['code'])){
			$util = new \Spark\Wechat\WechatUtil($this->wxConfig['appid'],$this->wxConfig['appsecret']);
			$ret = $util->getOAuth2AccessToken($_GET['code']);
			if($ret&&$ret->openid){
				session('wechat_id-'.$this->token,$ret->openid);
				if ($_GET['state']  == 'userinfo') {//2016-1-23
					$user = $util->getNewUserInfo($ret->openid,$ret->access_token);
					if($user&&$user->openid){
						$w = M('wechat_user')->where(['open_id'=>$user->openid])->find();
						$u = M('juejin_users')->where(['open_id'=>$user->openid])->find();
						//if($w==null || empty($w['wechat_name'])){
						
							$data['token'] =$this->token;
							$data['open_id'] = $user->openid;
							$data['wechat_name'] = $user->nickname;
							$data['sex'] = $user->sex;
							$data['language'] = $user->language;
							$data['country'] = $user->country;
							$data['province'] = $user->province;
							$data['headimgurl'] = $user->headimgurl;
							$data['update_time'] = time();
							if($w==null){
								M('wechat_user')->add($data);
							}
							else{
								M('wechat_user')->where(['id'=>$w['id']])->save($data);
							}

							$w = M('wechat_user')->where(['open_id'=>$user->openid])->find();
							$udata['token'] =$this->token;
							$udata['open_id'] =$user->openid;
							$udata['create_time'] =time();
							$udata['update_time'] =time();
							$udata['last_login_time'] =time();
							$udata['shareid'] = 0;
							$udata['integral'] = 0;
							$udata['last_login_ip'] =time();
							$udata['headimgurl'] = $user->headimgurl;
							if($u==null){
								M('juejin_users')->add($udata);
								//var_dump(M('juejin_users')->getLastSql());die();
							}
						//}
					}			
				}
				header('location:'.urldecode(session('ORIGIN_URL')).'#wechat_redirect');
				exit('正在跳转...');
			}
			else{
				$this->assign('message','获取用户信息失败！ERR:'.json_encode($ret));
				$this->assign('detail','<code>'.__SELF__.'</code><br/>');
				exit("获取用户信息失败");
				$this->display('Public:error');
			}
		}
		else {
			$this->assign('message','获取oauth 授权code失败！');
			exit("获取oauth 授权code失败！");
			$this->display('Public:error');
		}
	}
	
	
}